-- WatchBonusM
-- created by zouyb
-- watch奖励模块

require "game/base/encrypt/MyBase64";

module("WatchBonusM", package.seeall);

local watchBonusList = {};

local WATCH_BONUS_CHECK_INTERVAL = 60;

local checkWatchBonus;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下special_skill_info信息表
    local watch_bonus_CSV = get_watch_bonus_CSV();
    for i = 1, #watch_bonus_CSV do
        watchBonusList[watch_bonus_CSV[i].id] = watch_bonus_CSV[i];
    end

    watch_bonus_CSV = {};
end

-- 模块初始化操作
function init()
    loadCsv();

	syncConfig();

    -- 启动获取奖励信息调度器
    if isIosPlatform() and not ScheduleM.isSchemeAlive("WatchBonusM") then
        ScheduleM.createScheme("WatchBonusM", checkWatchBonus, WATCH_BONUS_CHECK_INTERVAL, true)
	end
end

-- 检索
function query(cmd, path)
    local m = watchBonusList[cmd];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 初始时，下发配置到手机本地
function syncConfig()
    if isIosPlatform() then      
        -- 更新道具名称
        for _, info in pairs(watchBonusList) do
           if info["bonus_type"] == 1 then
                info["name"] = MyBase64.encode(ItemM.query(tonumber(info["bonus_attrib"]), "name"));
           elseif info["bonus_type"] == 2 then
               info["name"] = MyBase64.encode(FieldsM.getFieldName(info["bonus_attrib"]));
           else
               info["name"] = "????";
           end
        end
        
        local config = { grid_data = watchBonusList };
        
        local str = json.encode(config);
        print("watch配置："..str);
        callOCFunc("syncWatchBonusConfig", { config = str });
   end
end

-- 删除奖励记录
function removeBonusRecord(ids)
    for _,id in pairs(ids) do
        print("清除watch奖励记录:"..id);
        if isIosPlatform() then
			callOCFunc("clearWatchBonusById", { id = id });	
		end
	end
end

-- 定时检查
function checkWatchBonus()
	if isIosPlatform() then
		if not ME or not ME.isInGame then
			-- 尚未进入游戏，不检查
			return;
		end

		local bonusStr = callOCFunc("getWatchBonusList");
		local bonusList = json.decode(bonusStr, 1);
		-- printTable(bonusList, "watch奖励列表");
		if #bonusList > 0 then
			Operation.cmd_watch_bonus_list(bonusList);
		end	
    end
end
-- windows测试奖励发送
function testBonusSend()
    local bonusStr = "[ { \"id\" : \"LJLSDF-SFDS1\", \"bonus\":[{\"id\":\"1\", \"count\":\"1\"}, {\"id\":\"5\", \"count\":\"7\"}] },";
    bonusStr = bonusStr .. "{ \"id\" : \"LJLSDF-SFDS2\", \"bonus\":[{\"id\":\"2\", \"count\":\"2\"}, {\"id\":\"4\", \"count\":\"3\"}] } ]";

    local bonusList = json.decode(bonusStr, 1);
    printTable(bonusList, "watch奖励列表");
    Operation.cmd_watch_bonus_list(bonusList);
end

